package cn.bearspark.user.provider.dao.buffer;

import cn.bearspark.framework.redis.starter.buffer.list.RedisBaseListBuffer;
import cn.bearspark.user.provider.dao.key.UserBufferKeyBuilder;
import cn.bearspark.user.provider.dao.mapper.UserFollowMapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 用户关注者 id 列表的缓存器
 *
 * @author f
 */
@Component
public class FanIdListBuffer extends RedisBaseListBuffer<Long> {

    /**
     * 设置粉丝的最多数量，默认是 十万，考虑到一个用户的粉丝数可能是 1亿，这个值比较小
     * <p>
     * 当一个用户的粉丝数是 1亿 时，他的粉丝 id 列表将会占用 762MB，此时就需要考虑一下 分段存储 用户的粉丝 id
     */
    private static final int MAX_FAN_NUM = 100000;

    private final UserFollowMapper userFollowMapper;

    private final UserBufferKeyBuilder userBufferKeyBuilder;

    public FanIdListBuffer(RedisTemplate<String, Object> redisTemplate,
                           UserFollowMapper userFollowMapper,
                           UserBufferKeyBuilder userBufferKeyBuilder) {
        super(redisTemplate);
        this.userFollowMapper = userFollowMapper;
        this.userBufferKeyBuilder = userBufferKeyBuilder;
    }

    /**
     * 获取指定用户所有粉丝的用户 id
     *
     * @param userId 指定的用户 id
     * @return 指定用户所有粉丝的用户 id 集合
     */
    public List<Long> listFanId(long userId) {
        return super.range(
                userBufferKeyBuilder.buildFansIdKey(userId),
                0, MAX_FAN_NUM,
                () -> userFollowMapper.listFansId(userId, MAX_FAN_NUM)
        );
    }
}
